package com.myapp.api.config;

import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.ResultStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<?> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            HttpStatus status = HttpStatus.NOT_FOUND;
            JsonResult result = new JsonResult(ResultStatus.NOT_FOUND, e.getMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else if (e instanceof java.lang.IllegalStateException) {
            HttpStatus status = HttpStatus.UNAUTHORIZED;
            JsonResult result = new JsonResult(ResultStatus.TOKEN_EXPIRED, e.getMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
            JsonResult result = new JsonResult(ResultStatus.SERVER_ERROR, e.getMessage());
            return new ResponseEntity<JsonResult>(result, status);
        }
    }
}
